package com.coai.message.repository

import com.coai.message.model.Conversation
import com.coai.message.model.ConversationType
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository

@Repository
interface ConversationRepository : JpaRepository<Conversation, String> {
    
    @Query("""
        SELECT c FROM Conversation c
        JOIN ConversationParticipant cp ON c.id = cp.conversationId
        WHERE cp.userId = :userId
        ORDER BY c.lastMessageTime DESC NULLS LAST, c.createdAt DESC
    """)
    fun findByUserId(userId: String): List<Conversation>
    
    @Query("""
        SELECT c FROM Conversation c
        WHERE c.type = :type
        AND EXISTS (
            SELECT 1 FROM ConversationParticipant cp1
            WHERE cp1.conversationId = c.id AND cp1.userId = :user1Id
        )
        AND EXISTS (
            SELECT 1 FROM ConversationParticipant cp2
            WHERE cp2.conversationId = c.id AND cp2.userId = :user2Id
        )
    """)
    fun findDirectConversation(user1Id: String, user2Id: String, type: ConversationType): Conversation?
}
